;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.WjServicePartDetail", [])
        .controller("WjServicePartDetailCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "EventBus", "$filter", function ($scope, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, EventBus, $filter) {

            $scope.tabFlag = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            // 列表查询条件
            $scope.condition = {};
            // 表格列配置信息
            $scope.toolbarConfig = {showMateriel: false};
            // 表格信息
            $scope.tableConfig = {
                fixedWidth: 120,
                scrollWidth: 1400,
                tableCol: [

                    {
                        name: "保养件类型",
                        dataField: "typeDesc",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "产品型号",
                        dataField: "proModelDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialDesc",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "单台用量",
                        dataField: "singleUsage",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "更换周期",
                        dataField: "changePeriod",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "创建时间",
                        dataField: "createdTime",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };
            // 切换配置表格列展示隐藏
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };
            // 设置表格宽度
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };
            // 当前选中行
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.markInfo = {
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.dataList = [];

            $scope.search = function (curPage) {
                if (curPage) $scope.pageInfo.curPage = curPage;
                getDataList();
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {

                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                    });
                }
            };
            EventBus.Subscribe("onMaterialChange", materialChange);

            function materialChange() {
                //detailInfo.materialsList
                let checkArr = $scope.detailInfo.materialsList;
                if (checkArr && checkArr.length > 0) {
                    if (checkArr.length > 1) {
                        ybWidget.ShowMessage("请选择一条零件", MESG_TYPE.Error);
                        return;
                    } else {
                        $scope.detailInfo.materialNo = checkArr[0].materialsNo;
                        $scope.detailInfo.materialDesc = checkArr[0].materialsDes;
                    }
                }
            };
            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange");
            });

            function getDataList() {
                $scope.markInfo.allChecked = false;
                var url = '/wjServicePartDetail/list';
                let varCondition = angular.copy($scope.condition);
                var param = {
                    filters: varCondition,
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    if (!res.value) return;

                    angular.forEach(res.value.list, function (item) {
                        item.isChecked = false;
                        item.createdTime = $filter("YbDate")(item.createdTime, 'yyyy-MM-dd HH:mm:ss');
                    });

                    $scope.pageInfo.totalRows = res.value.total;
                    $scope.pageInfo.totalPages = res.value.pages;
                    $scope.dataList = res.value.list;
                });
            }


            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.detailInfo = {
                materialsList: []
            };

            // 切换标签页
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        $scope.detailInfo = {materialsList: []};
                        break;
                    default:
                        break;
                }
            };

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.editData = function (item) {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.detailInfo = JSON.parse(JSON.stringify(item));
                $scope.detailInfo.materialsList = [];
                $scope.changeTab(1);
            };

            $scope.delData = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    handleDelData(item.id);
                })
            };

            $scope.delDataBatch = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    handleDelData(selectedDatas.map(sm => sm.id).join(','));
                })
            };

            function handleDelData(idsStr) {
                var url = '/wjServicePartDetail/remove';
                ybHttp.Get('device', url, {ids: idsStr}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                });
            }


            // 选择代理商
            $scope.selectDealer = function () {
                var param = {
                    name: "代理商",
                    type: "dealer",
                    isPlatCompany: 1
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.agentName = data.companyName;
                    $scope.detailInfo.agentId = data.platOrgId;
                })
            };

            // 保存
            $scope.saveData = UserContextService.Debounce(function (argu) {
                saveDataFunc(argu);
            }, 500);

            function saveDataFunc(valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var url = '/wjServicePartDetail/saveOrUpdate';
                var param = angular.extend($scope.detailInfo);
                if ($scope.tabFlag.type == 0) {
                    param.id = null;
                }
                if (param.type) {
                    param.typeDesc = $filter("wjReport")(param.type);
                }
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            };

            // 取消
            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            // 导入
            $scope.importData = function () {
                var param = {
                    name: "保养件明细",
                    templateReqService: "device",
                    templateReqUrl: "/wjServicePartDetail/downTemplate",
                    importReqService: "device",
                    importReqUrl: "/wjServicePartDetail/importExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    $scope.search(1);
                });
            };
            // 导出
            $scope.exportParam = {
                allUrl: ybHttp.RequestUrl("device", "/wjServicePartDetail/exportAll")
            };


            $scope.selectAll = function () {
                angular.forEach($scope.dataList, function (item) {
                    item.isChecked = $scope.markInfo.allChecked;
                });
            };

            function checkAll() {
                var selectAllFlag = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAllFlag = false;
                        break;
                    }
                    selectAllFlag = true;
                }
                return selectAllFlag;
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    $scope.markInfo.allChecked = checkAll();
                }
            };


            // 初始化页面信息
            (function () {

                $scope.setFixedWidth();
                $scope.search(1);
            })()
        }])
    ;
})(window, window.angular);
